import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Layout from '../components/Layout.vue'
import Home from '../views/Home.vue'
import { tim, TIM } from '../tim'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: Login,
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/Logon.vue')
    },
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: 'home',
          name: 'home',
          component: Home
        },
        {
          path: 'first',
          name: 'first',
          component: () => import('../views/First.vue')
        },
        {
          path: 'discover',
          name: 'discover',
          component: () => import('../views/Discover.vue')
        },
        {
          path: 'user',
          name: 'user',
          component: () => import('../views/User.vue')
        },
        {
          path: 'user-info',
          name: 'userInfo',
          component: () => import('../views/UserInfo.vue')
        },
        {
          path: 'wallet',
          name: 'wallet',
          component: () => import('../views/Wallet.vue')
        },
        {
          path: 'settings',
          name: 'settings',
          component: () => import('../views/Settings.vue'),
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'address',
          name: 'address',
          component: () => import('../views/Address.vue'),
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'classify',
          name: 'classify',
          component: () => import('../views/Classify.vue'),
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'Detailpage',
          name: 'Detailpage',
          component: () => import('../views/Detailpage.vue'),
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'Discover',
          name: 'Discover',
          component: () => import('../views/Discover.vue'),
          meta: {
            requiresAuth: true
          }
        },
        {
          path: 'chat',
          name: 'chat',
          component: () => import('../views/Chat.vue'),
          meta: {
            requiresAuth: true
          }
        }
      ]
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 登录和注册页面不需要验证
  const publicPages = ['/', '/register']
  if (publicPages.includes(to.path)) {
    next()
    return
  }

  // 验证登录状态
  const token = sessionStorage.getItem('token')
  const imUser = sessionStorage.getItem('im_user')
  
  if (!token || !imUser) {
    next('/')
    return
  }

  try {
    const userData = JSON.parse(imUser)

    // 等待 SDK ready
    await new Promise((resolve, reject) => {
      let timeoutId

      const readyHandler = () => {
        clearTimeout(timeoutId)
        tim.off(TIM.EVENT.SDK_READY, readyHandler)
        tim.off(TIM.EVENT.SDK_NOT_READY, notReadyHandler)
        resolve()
      }

      const notReadyHandler = () => {
        clearTimeout(timeoutId)
        tim.off(TIM.EVENT.SDK_READY, readyHandler)
        tim.off(TIM.EVENT.SDK_NOT_READY, notReadyHandler)
        reject(new Error('SDK not ready'))
      }

      // 先注册事件监听
      tim.on(TIM.EVENT.SDK_READY, readyHandler)
      tim.on(TIM.EVENT.SDK_NOT_READY, notReadyHandler)

      // 尝试获取当前登录状态
      tim.getMyProfile()
        .then(profile => {
          if (profile.data?.userID === userData.userID) {
            // 如果已经登录了正确的账号，直接触发 ready
            readyHandler()
          } else {
            // 如果未登录或登录了其他账号，尝试登录
            return tim.login({
              userID: String(userData.userID),
              userSig: userData.userSig
            })
          }
        })
        .catch(() => {
          // 如果获取状态失败，尝试登录
          return tim.login({
            userID: String(userData.userID),
            userSig: userData.userSig
          })
        })
        .catch(error => {
          console.error('IM 登录失败:', error)
          reject(error)
        })

      // 设置超时
      timeoutId = setTimeout(() => {
        tim.off(TIM.EVENT.SDK_READY, readyHandler)
        tim.off(TIM.EVENT.SDK_NOT_READY, notReadyHandler)
        reject(new Error('SDK ready 超时'))
      }, 10000)
    })

    next()
  } catch (error) {
    console.error('登录检查失败:', error)
    // 登录失败时，清除会话并返回登录页
    sessionStorage.clear()
    next('/')
  }
})

export default router
